package com.jhinwins.equipmenteb.equipmentebserver.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.jhinwins.equipmenteb.equipmentebserver.dao.UserDao;
import com.jhinwins.equipmenteb.equipmentebserver.entity.UserBean;
import com.jhinwins.equipmenteb.equipmentebserver.service.UserService;
import com.jhinwins.equipmenteb.equipmentebserver.utils.UserUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    private UserDao userDao;

    @Autowired
    public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public JSONObject regist(UserBean userBean) {
        UserBean save = userDao.save(userBean);
        return (JSONObject) JSONObject.toJSON(save);
    }

    @Override
    public JSONObject login(String username, String password) {
        JSONObject info = new JSONObject();
        try {
//            SecurityUtils.getSubject().login(new UsernamePasswordToken(username, password));
            UserBean userBean = userDao.findByUsername(username);
            if (password.equals(userBean.getPassword())) {
                UserUtils.curUser = userBean;
            } else {
                throw new AuthenticationException();
            }
            info.put("loginState", "SUCCESS");
        } catch (UnknownAccountException e) {
            //帐号错误
            info.put("loginState", "ERROR_ACCOUNT");
        } catch (IncorrectCredentialsException e) {
            //密码错误
            info.put("loginState", "ERROR_PASSWORD");
        } catch (AuthenticationException e) {
            //验证出错
            info.put("loginState", "ERROR_AUTH");
        } catch (Exception e) {
            //其他
            info.put("loginState", "UNKNOW_ERROR");
        }
        return info;
    }

    @Override
    public UserBean userExistence(String username) {
        return userDao.findOne(Example.of(new UserBean(username)));
    }
}
